// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0
  },
  handleChooseAddress(){
    wx.chooseAddress({
      success:(res)=>{
        wx.setStorageSync("address",res)
      }
    })
  },
  handlePay(){
    const address=this.data.address
    if (!address.userName){
      wx.showToast({
        title:"请选择收货地址"
      })
      return;
    }else if(this.data.totalNum===0){
      wx.showToast({
        title:"请选择商品"
      })
      return;
    }else {
      wx.navigateTo({
        url:'/pages/pay/pay'
      })
    }
  },
  handleItemNumEdit(e){
    const operation=e.currentTarget.dataset.operation
    const goods_id=e.currentTarget.dataset.id
    let cart =this.data.cart
    const index=cart.findIndex(v=>v.goods_id===goods_id)
    if (cart[index].num===1&&operation===-1){
      wx.showModal({
        title:'提示',
        content:'是否删除该商品？',
        success:res=>{
          if (res.confirm){
            cart.splice(index,1)
            this.setCart(cart)
          }else if (res.cancel){
            console.log("点击取消");
          }
        }
      })
    }else {
      cart[index].num+=operation
      this.setCart(cart)
    }

  },
  setCart(cart){
    let allChecked = true;
    let totalPrice=0;
    let totalNum=0;
    cart.forEach(v=>{
      if (v.checked){
        totalPrice+=v.num*v.goods_price;
        totalNum +=v.num
      }else {
        allChecked=false
      }
    })
    allChecked=cart.length!==0?allChecked:false
    this.setData({
      cart,
      totalNum,
      totalPrice,
      allChecked
    })
    wx.setStorageSync("cart",cart);
  },
  handleItemChange(e){
    const goods_id=e.currentTarget.dataset.id
    let cart=this.data.cart
    let index=cart.findIndex(v=>v.goods_id===goods_id)
    cart[index].checked=!cart[index].checked
    this.setCart(cart)
  },
  handleItemAllCheck(){
    let cart=this.data.cart
    let allChecked=this.data.allChecked
    allChecked=!allChecked
    cart.forEach(v=>v.checked=allChecked)
    this.setCart(cart)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const address=wx.getStorageSync("address")
    const cart=wx.getStorageSync("cart")||[]
    this.setData({
      address
    })
    this.setCart(cart)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})